package nl.saxion.act.servlet;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import nl.saxion.act.dao.AuctionDAO;
import nl.saxion.act.dao.CatagoryDAO;
import nl.saxion.act.dao.PersonDAO;
import nl.saxion.act.db.DatabaseManager;
import nl.saxion.act.wt.Person;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private DatabaseManager dbMan;
	private ServletContext context;

	public void init() throws ServletException {
		context = this.getServletContext();
		dbMan = (DatabaseManager) context.getAttribute("dbMan");

	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, java.io.IOException {
		if(request.getParameter("Action").equals("newUser")){
			CatagoryDAO catagory = new CatagoryDAO(dbMan);
			request.setAttribute("catagories", catagory.getAllCatagory() );
			
			RequestDispatcher view = context.getRequestDispatcher("/newUser.jsp");
			view.forward(request, response);
		} else{
			System.out.println("fout");
		}
		
		
	
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, java.io.IOException {
		try {

			PersonDAO personDAO = new PersonDAO(dbMan);
			Person p = personDAO.login(request.getParameter("username"),
					request.getParameter("password"));

			if (p != null) {
				HttpSession session = request.getSession(true);
				session.setAttribute("currentSessionUser", "yes");

				session.setAttribute("personID", p.getId() );
				response.sendRedirect("VeilingServlet?Action=NOTHING"); //logged-in page

			}

			else{
				response.sendRedirect("invalidLogin.jsp"); // error page
			}
		}

		catch (Throwable theException) {
			System.out.println(theException);
		}
	}
}
